﻿using System;
using System.Collections.Generic;
using System.Xml;

namespace Jayden.Dll.Core.Translations
{
	public class XmlTranslator : DictionaryTranslator
	{
		public XmlTranslator(string lang) : this(string.Empty, lang) { }
		public XmlTranslator(string source, string lang) : base(source, lang) { }

		public void Load(string path)
		{
			XmlDocument document = new XmlDocument();
			document.Load(path);
			XmlNodeList translations = document.SelectNodes("Translation/Entry");
			XmlAttribute source = document.DocumentElement.Attributes["source"];
			XmlAttribute lang = document.DocumentElement.Attributes["lang"];
			if (source != null && source.Value != SourceLang)
				throw new Exception("Invalid source.");
			if (lang.Value != Lang)
				throw new Exception("Invalid lang.");
			foreach (XmlNode node in translations)
			{
				XmlAttribute value = node.Attributes["value"];
				if (value != null)
					Add(node.Attributes["key"].Value, value.Value);
				else
					Add(node.Attributes["key"].Value, null);
			}
		}

		public void Save(string path)
		{
			XmlDocument document = new XmlDocument();
			XmlElement root = document.CreateElement("Translation");
			XmlAttribute lang = document.CreateAttribute("lang");
			root.Attributes.Append(lang);
			lang.Value = Lang;
			document.AppendChild(root);
			if(!string.IsNullOrWhiteSpace(SourceLang))
			{
				root.Attributes.Append(lang);
				XmlAttribute source = document.CreateAttribute("source");
				root.Attributes.Append(source);
				source.Value = SourceLang;
			}
			foreach (KeyValuePair<string, string> pair in this)
			{
				XmlElement translation = document.CreateElement("Entry");
				root.AppendChild(translation);
				XmlAttribute key = document.CreateAttribute("key"); ;
				XmlAttribute value = document.CreateAttribute("value"); ;
				translation.Attributes.Append(key);
				key.Value = pair.Key;
				if (pair.Value != null)
				{
					value.Value = pair.Value;
					translation.Attributes.Append(value);
				}
			}
			document.Save(path);
		}
	}
}
